2. 使用redux

安装redux

1
cnpm install redux

安装react-redux

1
cnpm install react-redux

使用

在src下创建store文件夹
store/index.js

1
2
3
4
5
6
import { createStore } from 'redux'
import reducer from './reducer'

const store = createStore(reducer)

export default store;

store/reducer.js

1
2
3
4
5
const defaultState = {};

export default (state = defaultState, action ) => {
return state;
}

App.js中使用Provider将store下放

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import React, { Component } from 'react';
import Header from './common/header';
import store from './store';
import { Provider } from 'react-redux';


class App extends Component {
render() {
return (
<Provider store={store}>
<Header />
</Provider>
);
}
}

export default App;

header/index.js中使用connect与store进行连接

1
2
3
4
5
6
7
8
9
10
11
const mapStateToProps = (state) => {
return {

}
}

const mapDispathToProps = (dispatch) => {
return {

}
}

1
2
3
4
import { connect } from 'react-redux';
...
...
export default connect(mapStateToProps, mapDispathToProps)(Header);

代码地址